<template>
  <div v-if="!isAdding">
    <el-select
      v-model="currentValue.day"
      placeholder="有限时间"
      clearable
      @change="handleChange"
      style="width: 400px"
    >
      <el-option
        v-for="(item, index) in dataList"
        :key="index"
        :label="item.label"
        :value="item.value"
      ></el-option>
      <!-- <template #footer>
        <el-button text bg size="small" type="primary" @click="onAddOption">自定义</el-button>
      </template> -->
    </el-select>
  </div>
  <div v-else>
    <el-date-picker
      v-model="tempTime"
      :editable="false"
      type="datetimerange"
      range-separator="~"
      start-placeholder="开始时间"
      end-placeholder="截止时间"
      value-format="YYYY-MM-DD HH:mm:ss"
      @change="handleChangeTime"
      style="width: 340px"
      :default-time="defaultTime"
    />
    <el-button @click="onAddOpen">取消</el-button>
  </div>
</template>
<script setup>
import { ref, watch } from "vue";
const isAdding = ref(false);
const tempTime = ref();
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)];
const props = defineProps({
  effectiveValue: {
    type: Object,
    default: () => ({
      day: "",
      begin: "",
      end: "",
    }),
  },
  effectiveType: {
    type: Number,
    default: 1,
  },
});

const dataList = ref([
  {
    label: "长期有效",
    value: -1,
  },
  {
    label: "7天",
    value: 7,
  },
  {
    label: "半个月",
    value: 15,
  },
  {
    label: "一个月",
    value: 30,
  },
]);
const emit = defineEmits(["change"]);
const currentValue = ref(props.effectiveValue);
const types = ref(props.effectiveType);

watch(
  (newVal) => {
    currentValue.value = props.effectiveValue;
    if (currentValue.value.day == 0) {
      currentValue.value.day = 7;
    }
    // console.log(currentValue.value);

    types.value = props.effectiveType;
  },
  { immediate: true }
);
const handleChange = (val) => {
  emitChange();
};
const onAddOption = () => {
  isAdding.value = true;
  types.value = 2;
  currentValue.value.day = "";
  emitChange();
};
const onAddOpen = () => {
  isAdding.value = false;
  types.value = 1;
  currentValue.value.begin = "";
  currentValue.value.end = "";
  tempTime.value = [];
  emitChange();
};
function handleChangeTime(val) {
  if (val) {
    const [startTime, endTime] = val;
    props.effectiveValue.begin = startTime;
    props.effectiveValue.end = endTime;
  } else {
    props.effectiveValue.begin = "";
    props.effectiveValue.end = "";
  }
  emitChange();
}

const emitChange = () => {
  emit("change", {
    day: currentValue.value.day,
    begin: currentValue.value.begin,
    end: currentValue.value.end,
    effectiveType: types.value,
  });
};
</script>
